import Vue from 'vue'
import Router from 'vue-router'
import Menus from './menu.js'
Vue.use(Router)

const routerPush = Router.prototype.push
Router.prototype.push = function push(location) {
    return routerPush.call(this, location).catch(error => error)
}

import login from '@/views/login.vue'
import index from '@/views/index.vue'

//用户管理
import userManageVue from '@/views/userManage/userManage.vue'

//角色管理
import roleManageVue from '@/views/roleManage/roleManage.vue'

//车辆管理
import carManageVue from '@/views/carManage/carManage.vue'

let routes = [
    { path: '/', redirect: '/login' },
    { path: '/login', name: 'login', component: login, meta: { normalRouteView: true } },
    { path: '/index', name: 'index', component: index },

    { path: '/userManage', name: 'userManage', component: userManageVue },

    { path: '/roleManage', name: 'roleManage', component: roleManageVue },

    { path: '/carManage', name: 'carManage', component: carManageVue },
];

let tmpMenus = [];
Menus.forEach(v => {
    if (v.child) {
        v.child.forEach(k => {
            tmpMenus.push(k)
        })
    } else {
        tmpMenus.push(v)
    }
})
routes.forEach(v => {
    tmpMenus.forEach(k => {
        if (v.name === k.route) {
            v.meta = {
                resourceCode: k.resourceCode
            }
        }
    })
})
const router = new Router({
    routes: routes
})
router.beforeEach(async(to, from, next) => {
    if (to.path === '/login') {
        sessionStorage.removeItem('token');
        next();
    } else {
        let token = sessionStorage.getItem('token');
        if (!token) {
            next({ path: '/login' })
            return;
        }
    }
    let store = router.app.$store;
    let resourceCode = to.meta.resourceCode;
    let permission = store.state.main.permission;
    if (to.path !== '/login' && permission.length === 0) {
        store.dispatch('dealPermission', sessionStorage.getItem('token')).then(res => {
            dealStatus();
            dealPermission();
        }).catch(error => {
            next({ path: '/login' })
            return;
        })
    } else {
        dealStatus();
        dealPermission();
    }

    function dealPermission() {
        if (resourceCode) {
            let permission = store.state.main.permission;
            let hasPermission = false;
            permission.forEach(v => {
                if (v.resourceCode === resourceCode) {
                    hasPermission = true;
                }
            })
            if (hasPermission) {
                next();
            } else {
                next({ path: '/login' })
            }
        } else {
            next();
        }
    }

    function dealStatus() {
        if (to.meta && to.meta.normalRouteView) {
            store.commit('setNormalRouteView', true);
        } else {
            store.commit('setNormalRouteView', false);
        }
    }
})

export default router